package com.epalmpay.job;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.epalmpay.entity.YsFlowChargeOrder;
import com.epalmpay.enumdef.CommonEnum.RunStatus;
import com.epalmpay.enumdef.CommonEnum.TaskType;
import com.epalmpay.service.operator.ISysLogService;
import com.epalmpay.service.yunstream.IOilcardOrderService;
import com.epalmpay.util.DateUtil;



/***
 * 交易结果通知
 * @author Administrator
 *
 */
@Component
public class TradeNotifyTaskJob {

	private static final Logger logger = LoggerFactory.getLogger(TradeNotifyTaskJob.class);
	
	@Resource
	private ISysLogService sysLogService;
	
	@Resource
	private IOilcardOrderService oilcardOrderService;

	//每小时执行一次
	@Scheduled(cron = "0 0/60 * * * ?")
	public void job() {
		//计算扫码付的
		int  limit = 1;
		int  page = 0;
		int  pageSize = 20;
		List<YsFlowChargeOrder> flowChargeRecords = null;
		do {
			if (limit > 1) {
				page = (limit - 1) * pageSize;
			}
			logger.info("TradeNotifyTask 交易结果通知....游标移动:{}", page);
			flowChargeRecords = oilcardOrderService.searchNotifyErrorflowCharge(page, pageSize);
			logger.info("select {} records.", flowChargeRecords.size());
			if (flowChargeRecords != null ) {
				for(YsFlowChargeOrder flowCharge:flowChargeRecords){
					try {
						String tradeNo=flowCharge.getPayOrderNum();
						String outTradeNo=flowCharge.getSysOrderNumber();
						Integer price=flowCharge.getPayAmount();// price
						oilcardOrderService.finishFlowsPayNotify(tradeNo, outTradeNo);
					} catch (Exception e) {
						logger.error("id:" + flowCharge.getId() + " calculate exception.", e);
						StringBuffer sb = new StringBuffer();
						try {
							sysLogService.recordSysTaskLog(TaskType.FlowTradeNotifyTask.getType(),
									new Date(), RunStatus.Fail.getType(),
									//sb.append("流量卡充值交易订单Id:").append(flowCharge.getId()).append("流量卡充值交易，支付结果通知失败！").toString());
									null);
						} catch (Exception e1) {
							e1.printStackTrace();
							continue;
						}
					}	
				}
			}
			limit++;// 游标移动

		} while (!flowChargeRecords.isEmpty());
		
		StringBuffer sb = new StringBuffer(); 
		logger.info(sb.append("计划任务:")
				.append(TaskType.FlowTradeNotifyTask.getName())
				.append("通知日期:").append(DateUtil.fomatDate(new Date(), DateUtil.sdfDays)).append("执行成功！").toString());
		try {
			sysLogService.recordSysTaskLog(TaskType.FlowTradeNotifyTask.getType(),
					new Date(), RunStatus.Success.getType(),
					//sb.append("流量卡充值交易订单").append(DateUtil.fomatDate(new Date(), DateUtil.sdfTime)).append("执行成功！").toString());
					null);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}
}
